import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

from collections import Iterator
from functools import reduce
#偏函数调用
from functools import partial

classmates = ['Michael', 'Bob', 'Tracy']
print(classmates)

print("ASCII(%s) is %s" %('1',ord("1")))

def fact(n):
	if n==1:
		return n;
	return n*fact(n-1)
print("递归fact(%s)结果是===>%s"%('3',fact(3)))


def isIterable(obj):
	return isinstance(obj, Iterator)
x = (20)
print(isIterable([]))
t = (1,)
print(t)

#f(x)=x2
def f(x):
	return x*x

r = map(f,[1,2,3,4,5,6,7,8,9])

print("map(f,[1,2,3,4,5,6,7,8,9])==>(%s) is %s" %('1*9',list(r)))

print('%s==>转字符串%s' %('list(map(str,[1,2,3,4,5,6,7,8,9])))',list(map(str,[1,2,3,4,5,6,7,8,9]))))

L = []
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
    L.append(f(n))
print("(%s) is %s" %('1*9',L))


#再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, ...]上，这个函数必须接收两个参数，
#educe把结果继续和序列的下一个元素做累积计算，其效果就是：
#reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

def add(x,y):
	return x + y

n = reduce(add,[1,2,3,4])

print("reduce:(%s) =%d" %('1+2+3+..',n))

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def str2int(s):
    def fn(x, y):
        return x * 10 + y
    def char2num(s):
        return DIGITS[s]
    return reduce(fn, map(char2num, s))
print ("str2int(%s) =%d" %('1576',str2int('1576')))
 #还可以用lambda函数进一步简化成：

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def char2num(s):
    return DIGITS[s]

def str2int(s):
    return reduce(lambda x, y: x * 10 + y, map(char2num, s))

print("lambda函数 str2int (%s) = %d" %('1576',str2int('1576')))

def  is_old(n):
	return n%2 == 0

print ("%s过滤器==>%s" %('filter',list(filter(is_old,[1,2,3,6,5,8,7,9]))))

def multiplication(n):
	for i in range(1,n):
		for j in range(1,n):
			print("%d*%d=%2d" % (i, j, i*j),end=" "),
		print("\n")
multiplication(10);

#装饰函数
def log(func):
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper
#观察上面的log，因为它是一个decorator，所以接受一个函数作为参数，并返回一个函数。
#我们要借助Python的@语法，把decorator置于函数的定义处：
#调用now()函数，不仅会运行now()函数本身，还会在运行now()函数前打印一行日志：
@log
def now():
    print('2015-3-25')

now();

#100以内的奇数
def oddNum(num):
	return filter(lambda x:x%2 == 1,range(1,num));

for x in oddNum(100):
	print(x);

#可以简写成
print([item for item in filter(lambda x:x%2==1,range(1,100))]);

# #偏函数
# num = int(input('请输入一个数n'))

# def hs(m,n):
# 	return m%n

# y_100 = partial(hs,100)

# print('100对%d取余：'%num,y_100(num))


#!/usr/bin/env python3 
# -*- coding: utf-8 -*-

' a test module '

__author__ = 'xxxx'

def test():
    args = sys.argv
    if len(args)==1:
        print('Hello, world!')
    elif len(args)==2:
        print('Hello, %s!' % args[1])
    else:
        print('Too many arguments!')

if __name__=='__main__':
    test()

